package com.kefu.chat.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kefu.chat.mapper.*;
import com.kefu.chat.model.*;
import com.kefu.chat.vo.*;
import com.kefu.common.context.KefuContext;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.common.util.Assert;
import com.kefu.common.util.JacksonUtil;
import com.kefu.robot.model.RobotInfo;
import com.kefu.robot.service.RobotInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
@Transactional
public class ChatChannelService  extends AbstractKefuService<ChatChannel>  {
    @Resource
    private ChatMenuConfigPlanMapper chatMenuConfigPlanMapper;
    @Resource
    protected ChatChannelMapper chatChannelMapper;
    @Resource
    private ChatEvaluateMapper chatEvaluateMapper;
    @Resource
    private ChatPosterMapper chatPosterMapper;
    @Resource
    private ChatFaqMapper chatFaqMapper;
    @Resource
    private RobotInfoService robotInfoService;
    @Resource
    private ChatMenuConfigMapper chatMenuConfigMapper;
    @Resource
    private ChatChannelSideBarMapper chatChannelSideBarMapper;
    @Resource
    private ChatChannelExtModelMapper chatChannelExtModelMapper;

    @Override
    public boolean save(ChatChannel chatChannel) {
        Long count = chatChannelMapper.selectCount(Wrappers.lambdaQuery(ChatChannel.class)
                .eq(ChatChannel::getChannelName, chatChannel.getChannelName())
                .eq(ChatChannel::getChannelType, chatChannel.getChannelType())
                .eq(ChatChannel::getTenantId, KefuContext.getTid()));
        Assert.isTrue(count > 0, "渠道["+ chatChannel.getChannelName()+"]已经存在！");
        return super.save(chatChannel);
    }

    public ChatChannel getFromId(String id) {
        return chatChannelMapper.selectByPrimaryKey(id);
    }

     
    public ChatChannel getFromAppId(String appId) {
        return getOne(Wrappers.lambdaQuery(ChatChannel.class).eq(ChatChannel::getAppId,appId));
    }

    public void updateChannel(ChatChannel channel) {
        ChatChannel info = findById(channel.getChannelId());
        Assert.isNull(info, "渠道异常！");
        List<ChatChannel> chatChannels = chatChannelMapper.selectList(Wrappers.lambdaQuery(ChatChannel.class)
                .eq(ChatChannel::getChannelName, channel.getChannelName())
                .eq(ChatChannel::getChannelType, info.getChannelType())
                .eq(ChatChannel::getTenantId, KefuContext.getTid()));
        boolean flag = true;
        for (ChatChannel chatChannel : chatChannels) {
            if (!channel.getChannelId().equals(chatChannel.getChannelId())) {
                flag = false;
                break;
            }
        }
        Assert.isTrue(!flag, "渠道["+ channel.getChannelName()+"]已经存在！");
        updateById(channel);
    }

    @Override
    public void deleteById(String id) {
        super.deleteById(id);
        chatChannelSideBarMapper.delete(Wrappers.lambdaQuery(ChatChannelSideBar.class).eq(ChatChannelSideBar::getChannelId, id));
        chatChannelExtModelMapper.delete(Wrappers.lambdaQuery(ChatChannelExtModel.class).eq(ChatChannelExtModel::getChannelId, id));
        chatEvaluateMapper.delete(Wrappers.lambdaQuery(ChatEvaluate.class).eq(ChatEvaluate::getChannelId, id));
    }

    /**
     * 添加侧边栏
     */
    public ChatChannelSideBar addSidebarMenuInfo(ChatChannelSideBarInsertVo chatChannelSideBarVo) {
        ChatChannelSideBar info = chatChannelSideBarVo.convert();
        Integer sortNo = chatChannelSideBarMapper.getWeight(info.getChannelId());
        info.setSortNo(sortNo+1);
        chatChannelSideBarMapper.insert(info);
        logger.info("添加渠道侧边栏:{}", JacksonUtil.toString(info));
        return info;
    }

    public ChatChannelSideBar updateCusSidebarMenuInfo(ChatChannelSideBarUpdateVo chatChannelSideBarVo) {
        ChatChannelSideBar info = chatChannelSideBarVo.convert();
        chatChannelSideBarMapper.updateById(info);
        logger.info("更新渠道侧边栏:{}", JacksonUtil.toString(info));
        return info;
    }

    public ChatChannelSideBar deleteSidebarMenuInfo(String id) {
        ChatChannelSideBar info = chatChannelSideBarMapper.selectByPrimaryKey(id);
        Assert.isNull(info, "侧边栏已经删除！");
        chatChannelSideBarMapper.deleteByPrimaryKey(id);
        return info;
    }

    public List<ChatChannelSideBar> getSideBarListByChannelId(String channelId) {
        List<ChatChannelSideBar> chatChannelSideBars = chatChannelSideBarMapper.selectList(Wrappers.lambdaQuery(ChatChannelSideBar.class)
                .eq(ChatChannelSideBar::getChannelId, channelId)
                .eq(ChatChannelSideBar::getMenuStatus, 1)
                .orderByAsc(ChatChannelSideBar::getSortNo));
        return chatChannelSideBars;
    }

    public ChatChannelExtModel addExtModel(ChatChannelExtModelInsertVo chatChannelExtModelVo) {
        ChatChannelExtModel info = chatChannelExtModelVo.convert();
        chatChannelExtModelMapper.insert(info);
        logger.info("添加扩展功能:{}", JacksonUtil.toString(info));
        return info;
    }

    public ChatChannelExtModel deleteExtModel(String id) {
        ChatChannelExtModel info = chatChannelExtModelMapper.selectByPrimaryKey(id);
        Assert.isNotNull(info, "已被删除!");
        chatChannelExtModelMapper.deleteByPrimaryKey(id);
        logger.info("删除了扩展菜单：{}", info);
        return info;
    }

    public ChatChannelExtModel updateExtModel(ChatChannelExtModelUpdateVo chatChannelExtModelVo) {
        ChatChannelExtModel info = chatChannelExtModelVo.convert();
        chatChannelExtModelMapper.updateById(info);
        logger.info("更新扩展功能:{}", JacksonUtil.toString(info));
        return info;
    }

    public List<ChatChannelExtModel> getExtModelListByChannelId(String channelId, int modelType) {
        List<ChatChannelExtModel> chatChannelExtModels = chatChannelExtModelMapper.selectList(Wrappers.lambdaQuery(ChatChannelExtModel.class)
                .eq(ChatChannelExtModel::getChannelId, channelId).eq(ChatChannelExtModel::getExtModelType, modelType));
        return chatChannelExtModels;
    }

    public Page<ChatChannelSideBar> listSideBar(ChatChannelSideBarSearchVo search) {
        Page<ChatChannelSideBar> page = new Page<>(search.getPageNo(), search.getPageSize(), true);
        page = chatChannelSideBarMapper.selectPage(page, search.lambdaQuery());
        return page;
    }

    public Page<ChatChannelExtModel> listExtModel(ChatChannelExtModelSearchVo search) {
        Page<ChatChannelExtModel> page = new Page<>(search.getPageNo(), search.getPageSize(), true);
        page = chatChannelExtModelMapper.selectPage(page, search.lambdaQuery());
        return page;
    }

    public Page<ChatChannel> listChannel(ChatChannelSearchVo search) {
        Page<ChatChannel> page = searchLambdaPage(search);
        return page;
    }

    public ChatChannelVo detailById(String id) {
        ChatChannel channel = findById(id);
        Assert.isNull(channel, "渠道已被删除！");
        RobotInfo robotInfo = robotInfoService.getByRobotNo(channel.getTenantId(), channel.getRobotNo());
        if (robotInfo != null) {
            channel.setRobotName(robotInfo.getRobotName());
            channel.setRobotIcon(robotInfo.getRobotIcon());
        }
        ChatChannelVo chatChannelVo = BeanUtil.toBean(channel, ChatChannelVo.class);
        if (Objects.equals(1, chatChannelVo.getFaqMode()) && StrUtil.isNotBlank(chatChannelVo.getFaqId())) {
            ChatFaq chatFaq = chatFaqMapper.selectByPrimaryKey(chatChannelVo.getFaqId());
            chatChannelVo.setFaq(chatFaq);
        }
        if (Objects.equals(1, chatChannelVo.getMenuMode())
                && StrUtil.isNotBlank(chatChannelVo.getMenuConfigPlanId())) {
            String configId = chatChannelVo.getMenuConfigPlanId();
            ChatMenuConfigPlan config = chatMenuConfigPlanMapper.selectByPrimaryKey(configId);
            if (Objects.nonNull(config) && StrUtil.isNotBlank(config.getMenus())) {
                List<ChatMenuConfig> chatMenuConfigs = chatMenuConfigMapper.selectList(Wrappers.lambdaQuery(ChatMenuConfig.class)
                        .in(ChatMenuConfig::getId, Arrays.asList(config.getMenus().split(","))));
                config.setChatMenuConfigList(chatMenuConfigs);
            }
            chatChannelVo.setChatMenuConfigPlan(config);
        }
        if (Objects.equals(1, chatChannelVo.getPosterMode()) && StrUtil.isNotBlank(chatChannelVo.getPosterIds())) {
            List<ChatPoster> chatPosters = chatPosterMapper.selectList(Wrappers.lambdaQuery(ChatPoster.class)
                    .in(ChatPoster::getId, Arrays.asList(chatChannelVo.getPosterIds().split(","))));
            chatChannelVo.setChatPosters(chatPosters);
        }
        chatChannelVo.setSideBarList(getSideBarListByChannelId(chatChannelVo.getChannelId()));
        chatChannelVo.setPcExtModelList(getExtModelListByChannelId(chatChannelVo.getChannelId(), 1));
        return chatChannelVo;
    }
}
